package com.jams.goodox.activity.serve.enterprise;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.adapter.viewHolder.RentingDetailViewHolder;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.Comment;
import com.jams.goodox.entity.Neighborhood;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.NeighborCommentsResp;
import com.jams.goodox.entity.resp.NeighborDetailResp;
import com.jams.goodox.entity.resp.UserLisResp;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.RentingService;
import com.jams.goodox.utils.CircleManager;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DeviceUtils;
import com.jams.goodox.utils.DialogUtils;
import com.jams.goodox.utils.ImageUtils;
import com.jams.goodox.utils.MessageDialog;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.utils.ViewUtils;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

import static com.jams.goodox.activity.serve.enterprise.EnterpriseCooperationActivity.RESULT_CODE;

/**
 * 企业合作详情(租房详情类似)
 */
public class EnterpriseCooperationDetailActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.rcv_neighbor_comment)
    RefreshRecyclerView rcvNeighborComment;
    @Bind(R.id.sdv_circle_detail)
    SwipeRefreshLayout sdvCircleDetail;
    @Bind(R.id.iv_neighbour_bottom_left)
    ImageView ivNeighbourBottomLeft;
    @Bind(R.id.tv_neighbour_bottom_left)
    TextView tvNeighbourBottomLeft;
    @Bind(R.id.ly_neighbor_bottom_group)
    LinearLayout lyNeighborBottomGroup;
    private TextView tvRightMenu;

    private RentingDetailViewHolder neighborDetailViewHolder;
    private Neighborhood neighborhood;
    private String id;
    private List<Comment> commentDataList;
    private int totalComments;//总的评论数
    private int curPage;

    public static final String COOPERATION = "COOPERATION";
    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_renting_detail;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"详情");
        commentDataList = new ArrayList<>();
        tvRightMenu = (TextView) findViewById(R.id.head_right_tv);
        id = StringUtils.newString(getIntent().getStringExtra(COOPERATION));
        sdvCircleDetail.setOnRefreshListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_cooperation_detail, null);
        neighborDetailViewHolder = new RentingDetailViewHolder(this, view);
        rcvNeighborComment.setLayoutManager(new RefreshLinearLayoutManager(this));
        rcvNeighborComment.setHasFixedSize(true);
        RecycleCommonAdapter commonAdapter;
        rcvNeighborComment.setAdapter(commonAdapter = new RecycleCommonAdapter<Comment>(this, commentDataList, R.layout.renting_comment_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, Comment item, int position) {
                setCommentData(helper, item, position);
            }

        });
        rcvNeighborComment.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                getCommentList();
            }
        });
        commonAdapter.setHeaderView(view);
        showLoading();
        onRefresh();
    }

    //获取邻里详情
    private void getNeighborDetail() {
        enqueue(createCallService(RentingService.class).getNeighborDetail(StringUtils.newString(id)), new RetrofitCallbackListener<NeighborDetailResp>() {
            @Override
            public void onSuccess(Call<NeighborDetailResp> call, NeighborDetailResp result) {
                try {
                    sdvCircleDetail.setRefreshing(false);
                    neighborhood = result.getData();
                    setRightAction();
                    setPraiseStatus();
                    getJoinList(false);
                    lyNeighborBottomGroup.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                try {
                    sdvCircleDetail.setRefreshing(false);
                    neighborDetailViewHolder.setCommentTipStatus(true);
                    misLoading();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //获取留言列表
    private void getCommentList() {
        enqueue(createCallService(RentingService.class).getNeighborComments(StringUtils.newString(id), curPage, AppConfig.PagSize), new RetrofitCallbackListener<NeighborCommentsResp>() {
            @Override
            public void onSuccess(Call<NeighborCommentsResp> call, NeighborCommentsResp result) {
                misLoading();
                try {
                    sdvCircleDetail.setRefreshing(false);
                    rcvNeighborComment.loadMoreComplete();
                    if(result.getData() != null){
                        if (curPage == 1) {
                            commentDataList.clear();
                        }
                        rcvNeighborComment.setCanLoadMore(result.getData().getPageInfo().isHasMore());
                        commentDataList.addAll(result.getData().getResultList());
                        curPage++;
                        if (!CollectionUtils.hasData(commentDataList)) {
                            neighborDetailViewHolder.setCommentTipStatus(true);
                        } else {
                            neighborDetailViewHolder.setCommentTipStatus(false);
                        }
                        totalComments = result.getData().getPageInfo().getTotal();
                        neighborDetailViewHolder.setCommentCounts(totalComments);
                        rcvNeighborComment.notifyData();
                    }else {
                        neighborDetailViewHolder.setCommentTipStatus(true);
                    }
                    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                misLoading();
                try {
                    sdvCircleDetail.setRefreshing(false);
                    rcvNeighborComment.loadMoreComplete();
                    neighborDetailViewHolder.setCommentTipStatus(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //获取加入、点赞的人的列表
    private void getJoinList(final boolean isUpdate) {
        enqueue(createCallService(RentingService.class).getJoinList("neighbor", StringUtils.newString(neighborhood.getId()), 1, 5), new RetrofitCallbackListener<UserLisResp>() {
            @Override
            public void onSuccess(Call<UserLisResp> call, UserLisResp result) {
                try {
                    if (result.getData() != null) {
                        sdvCircleDetail.setVisibility(View.VISIBLE);
                        if (!isUpdate) {//非局部刷新
                            neighborDetailViewHolder.setData(neighborhood, result.getData(),true); //显示username
                            //修改标签宽度
                            ViewUtils.setLabelWidth(mContext,neighborDetailViewHolder.tvLabel);
                            getCommentList();
                        } else {//局部刷新
                            neighborDetailViewHolder.updateJoinList(result.getData());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String msg) {
                misLoading();
                if (sdvCircleDetail != null) {
                    sdvCircleDetail.setRefreshing(false);
                }

            }
        });
    }

    //设置顶部右边菜单键
    private void setRightAction() {
        try {
            if (neighborhood == null) { //非空判断
                return;
            }
            if (isMyself(neighborhood.getUserSimple().getId())) {
                tvRightMenu.setText(R.string.delete);
                tvRightMenu.setVisibility(View.VISIBLE);
                tvRightMenu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delCircle(StringUtils.newString(neighborhood.getId()));
                    }
                });
            } else {
                tvRightMenu.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //检查是否是自己
    private boolean isMyself(String id) {
        if (id == null) {
            return false;
        } else if (id.equals(SePref.getUserId())) {
            return true;
        }
        return false;
    }

    //删除邻里
    private void delCircle(final String id) {
        DialogUtils.deleteConfirm(this, "确定删除？", new SuccessListener() {
            @Override
            public void success() {
                CircleManager.delCircle(mContext, id, new SuccessListener() {
                    @Override
                    public void success() {
                        setResult(1993);
                        finish();
                    }
                });
            }
        });
    }

    //回复
    public void replayMessage(final Comment item, final int position) {
        final boolean isMySendMessage = item.getFromUser().getId().equals(SePref.getUserId());
        if (isMySendMessage) {
            setIsMyselfMenu(item, position);
        } else {
            setIsOtherMenu(item);
        }
    }

    //设置本人底部弹出菜单
    private void setIsMyselfMenu(final Comment item, final int position) {
        String strArray[];
        strArray = new String[]{getString(R.string.delete), getString(R.string.copy)};
        MessageDialog.showBottomMenu(this, strArray, new MessageDialog.MenuDialogOnItemClickListener() {
            @Override
            public void onItemClick(int index) {
                switch (index) {
                    case 1:
                        DialogUtils.deleteConfirm((Activity) mContext, "确定删除该评论？", new SuccessListener() {
                            @Override
                            public void success() {
                                CircleManager.delComment(mContext, item.getId(), new SuccessListener() {
                                    @Override
                                    public void success() {
                                        setResult(RESULT_CODE);
                                        commentDataList.remove(position);
                                        neighborDetailViewHolder.setCommentCounts(totalComments - 1);
                                        rcvNeighborComment.notifyData();
                                        if (!CollectionUtils.hasData(commentDataList)) {
                                            neighborDetailViewHolder.setCommentTipStatus(true);
                                        } else {
                                            neighborDetailViewHolder.setCommentTipStatus(false);
                                        }
                                    }
                                });
                            }
                        });
                        break;
                    case 2:
                        DeviceUtils.copyToClipBoard((Activity) mContext, StringUtils.newString(item.getContent()));
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //不是本人的底部菜单
    private void setIsOtherMenu(final Comment item) {
        try {
            if (item == null || neighborhood == null) {//非空判断
                return;
            }
            String strArray[];
            strArray = new String[]{getString(R.string.copy), getString(R.string.message_pri_msg), getString(R.string.replay_comment)};
            MessageDialog.showBottomMenu(this, strArray, new MessageDialog.MenuDialogOnItemClickListener() {
                @Override
                public void onItemClick(int index) {
                    switch (index) {
                        case 1:
                            DeviceUtils.copyToClipBoard((Activity) mContext, item.getContent());
                            break;
                        case 2:
                            message(item.getFromUser());
                            break;
                        case 3:
                            Intent intent = new Intent(mContext, LeaveMessageActivity.class);//type =3 ,企业合作的回复
                            intent.putExtra("id", neighborhood.getId());
                            intent.putExtra("toUserId", item.getFromUser().getId());
                            intent.putExtra("msgId", item.getId());
                            intent.putExtra("toUserName", item.getFromUser().getNickName());
                            startActivityForResult(intent, 1991);
                            break;
                        default:
                            break;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //私信
    private void message(User userInfo) {
    }

    private void setPraiseStatus() {
        if (neighborhood == null) {//非空判断
            return;
        }
        if (neighborhood.isPraise()) {
            tvNeighbourBottomLeft.setText("已赞");
            ivNeighbourBottomLeft.setBackgroundResource(R.mipmap.good_icon_orange);
            tvNeighbourBottomLeft.setTextColor(ContextCompat.getColor(this, R.color.orange));
        } else {
            tvNeighbourBottomLeft.setText("点赞");
            ivNeighbourBottomLeft.setBackgroundResource(R.mipmap.good_icon);
            tvNeighbourBottomLeft.setTextColor(ContextCompat.getColor(this, R.color.font_main));
        }
    }

    @OnClick({R.id.lv_neighbor_detail_bottom_left, R.id.lv_neighbor_detail_bottom_right})
    public void onViewClicked(View view) {
        if (neighborhood == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.lv_neighbor_detail_bottom_left:
                if(Utils.isFastDoubleClick())return;
                try {
                    final int actionType;
                    if (neighborhood.isPraise()) {
                        actionType = 0;
                    } else {
                        actionType = 1;
                    }
                    CircleManager.praise(this, StringUtils.newString(neighborhood.getId()), actionType, new SuccessListener() {
                        @Override
                        public void success() {
                            if (actionType == 0) {
                                neighborDetailViewHolder.praise(false);
                                neighborhood.setPraise(false);
                            } else {
                                neighborDetailViewHolder.praise(true);
                                neighborhood.setPraise(true);
                            }
                            setPraiseStatus();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.lv_neighbor_detail_bottom_right:
                Intent intent = new Intent(mContext, LeaveMessageActivity.class);
                intent.putExtra("id", StringUtils.newString(neighborhood.getId()));
                startActivityForResult(intent, 1991);
                break;
        }
    }
    //设置评论数据
    private void setCommentData(RecycleCommonViewHolder helper,final Comment comment,final int position) {
        helper.setSimpleDraweeView(R.id.sdv_neighbour_comment_portrait, StringUtils.newString(ImageUtils.getSmallUrl(comment.getFromUser().getPortraitUrl())));
        helper.setText(R.id.tv_neighbor_comment_name, StringUtils.newString(comment.getFromUser().getNickName()));
        helper.setText(R.id.tv_neighbor_comment_time, StringUtils.newString(comment.getInTime()));
        if (comment.getToUser() == null || TextUtils.isEmpty(comment.getToUser().getId())) {
            helper.setText(R.id.tv_neighbor_comment_content, StringUtils.newString(comment.getContent()));
        } else {
            String content = "回复" + comment.getToUser().getNickName() + ":" + StringUtils.newString(comment.getContent());
            SpannableStringBuilder style = new SpannableStringBuilder(content);
            style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.main_theme)), 2, comment.getToUser().getNickName().length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ((TextView) helper.getView(R.id.tv_neighbor_comment_content)).setText(style);
        }
        helper.setOnItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                replayMessage(comment, position);
            }
        });
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                try {
                    sdvCircleDetail.setRefreshing(true);
                    curPage = 1;
                    getNeighborDetail();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1991) {
            switch (resultCode) {
                case 1992://评论成功
                    curPage = 1;
                    getCommentList();
                    break;
                default:
                    break;
            }
        }
    }


}
